import {
  ProSchemaValueEnumMap,
  ProSchemaValueEnumObj,
  ProSchemaValueEnumType,
} from '@ant-design/pro-components';

type FieldNames = {
  label?: string;
  value?: string | number;
};

type Options = { [key: string | number]: any };

export function optionsToValueEnum(
  options?: Options[],
  fieldNames: FieldNames = {
    label: 'label',
    value: 'value',
  },
): ProSchemaValueEnumObj | ProSchemaValueEnumMap {
  if (!options) {
    return {};
  }
  const endFieldNames = {
    label: fieldNames?.label || 'label',
    value: fieldNames?.value || 'value',
  };
  const res: { [key: string | number]: ProSchemaValueEnumType } = {};
  options.forEach((item) => {
    const value = item[endFieldNames.value];
    if ((typeof value === 'string' || typeof value === 'number') && item.value !== '') {
      res[item[endFieldNames.value]] = {
        text: item[endFieldNames.label],
      };
    }
  });
  return res;
}

export function formatOptions(
  options?: Options[],
  fieldNames: FieldNames = {
    label: 'label',
    value: 'value',
  },
): API.Select[] {
  if (!options) {
    return [];
  }
  const endFieldNames = {
    label: fieldNames?.label || 'label',
    value: fieldNames?.value || 'value',
  };
  return options.map((item) => {
    return {
      label: item[endFieldNames.label],
      value: item[endFieldNames.value],
    };
  });
}
